package org.ruixue.service;

import org.ruixue.response.BaseResponse;
import org.ruixue.util.ByteUtil;
import org.ruixue.util.DateUtil;
import org.ruixue.util.SnoGerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.ruixue.dao.oms.EcOrderMapper;
import org.ruixue.dao.oms.EcRefundItemMapper;
import org.ruixue.dao.oms.EcRefundMapper;
import org.ruixue.dao.oms.EcTradeMapper;
import org.ruixue.dao.oms.ShopMapper;
import org.ruixue.dao.yshop.StoreOrderMapper;
import org.ruixue.dao.yshop.UserMapper;
import org.ruixue.entity.oms.EcOrder;
import org.ruixue.entity.oms.EcRefund;
import org.ruixue.entity.oms.EcRefundItem;
import org.ruixue.entity.oms.EcTrade;
import org.ruixue.entity.oms.Shop;
import org.ruixue.entity.yshop.StoreOrder;
import org.ruixue.entity.yshop.StoreOrderExample;
import org.ruixue.entity.yshop.User;

import java.util.ArrayList;
import java.util.List;

@Service("refundService")
public class RefundService {

	/**
	 * OMS：网店表
	 */
	@Autowired
	private ShopMapper shopMapper;

	/**
	 * OMS：平台交易表
	 */
	@Autowired
	private EcTradeMapper ecTradeMapper;

	/**
	 * OMS:平台订单表
	 */
	@Autowired
	private EcOrderMapper ecOrderMapper;

	/**
	 * OMS：退款单
	 */
	@Autowired
	private EcRefundMapper ecRefundMapper;

	/**
	 * OMS：平台退款明细
	 */
	@Autowired
	private EcRefundItemMapper ecRefundItemMapper;

	/**
	 * 平台商城：订单表
	 */
	@Autowired
	private StoreOrderMapper storeOrderMapper;

	/**
	 * 平台商城：用户表
	 */
	@Autowired
	private UserMapper userMapper;

	/**
	 * 根据网店获取退款单信息
	 * 
	 * @return
	 * @throws Exception
	 */
	public BaseResponse downloadYiRefundWhole() throws Exception {
		// 时间戳
		Integer startTime = DateUtil.getTimeInMillis(-2);
		Integer endTime = DateUtil.getTimeInMillis(null);

		// 0 未退款
		List<Byte> refundStatusList = new ArrayList<Byte>();
		refundStatusList.add((byte) 0);

		// 查询平台商城订单表数据
		StoreOrderExample soExample = new StoreOrderExample();
		soExample.createCriteria().andAddTimeBetween(startTime, endTime) // 创建时间
				.andRefundStatusNotIn(refundStatusList); // 退款状态
		List<StoreOrder> storeOrderList = storeOrderMapper.selectByExample(soExample);
		if (storeOrderList != null && storeOrderList.size() == 0) {
			return new BaseResponse("true", "获取订单数量为0");
		}

		return this.downloadYiRefundData(null, storeOrderList);
	}
	
	/**
	 * 根据网店获取退款单信息
	 * 
	 * @param shopId
	 * @return
	 * @throws Exception
	 */
	public BaseResponse downloadYiRefund(String shopId) throws Exception {
		if (StringUtils.isBlank(shopId)) {
			return new BaseResponse("false", "shopId is null");
		}
		Shop shop = shopMapper.selectByPrimaryKeyShop(shopId);
		if (shop == null) {
			return new BaseResponse("false", "shop is null");
		}

		// 时间戳
		Integer startTime = DateUtil.getTimeInMillis(-2);
		Integer endTime = DateUtil.getTimeInMillis(null);

		// 0 未退款
		List<Byte> refundStatusList = new ArrayList<Byte>();
		refundStatusList.add((byte) 0);

		// 查询平台商城订单表数据
		StoreOrderExample soExample = new StoreOrderExample();
		soExample.createCriteria().andMerIdEqualTo(Integer.parseInt(shop.getAppKey())) // 商户ID
				.andAddTimeBetween(startTime, endTime) // 创建时间
				.andRefundStatusNotIn(refundStatusList); // 退款状态
		List<StoreOrder> storeOrderList = storeOrderMapper.selectByExample(soExample);
		if (storeOrderList != null && storeOrderList.size() == 0) {
			return new BaseResponse("true", "获取订单数量为0");
		}

		return this.downloadYiRefundData(shop, storeOrderList);
	}

	/**
	 * 保存退款信息
	 * 
	 * @param shop
	 * @param storeOrderList
	 * @return
	 * @throws Exception
	 */
	private BaseResponse downloadYiRefundData(Shop shop, List<StoreOrder> storeOrderList) {
		// 遍历循环
		for (int i = 0; i < storeOrderList.size(); i++) {
			StoreOrder storeOrder = storeOrderList.get(i);
			// 验证网店是否存在
			if(shop == null) {
				shop = shopMapper.selectByPrimaryKeyShop(storeOrder.getMerId().toString());
				if (shop == null) {
					return new BaseResponse("false", "shop is null");
				}
			}
			
			// 获取平台交易表
			EcTrade ecTradeParam = new EcTrade();
			ecTradeParam.setEcTradeCode(storeOrder.getOrderId());
			ecTradeParam.setShopId(shop.getShopId());
			EcTrade ecTrade = ecTradeMapper.selectByPrimaryKeyEcTrade(ecTradeParam);

			// 获取平台订单表
			EcOrder ecOrderParam = new EcOrder();
			ecOrderParam.setShopId(shop.getShopId());
			ecOrderParam.setEcTradeCode(storeOrder.getOrderId());
			EcOrder ecOrder = ecOrderMapper.selectByPrimaryKeyEcOrder(ecOrderParam);

			// 查询用户信息
			User user=userMapper.selectByPrimaryKey(storeOrder.getUid());
		
			// 新增或更新EC表
			if (ecTrade != null) {
				EcRefund ecRefund = new EcRefund();
				String refundId = SnoGerUtil.getUUID();

				ecRefund.setEcRefundCode(storeOrder.getOrderId());
				ecRefund.setPrjId(shop.getPrjId());
				ecRefund.setPrjName(shop.getPrjName());
				ecRefund.setShopId(shop.getShopId());
				ecRefund.setShopName(shop.getShopName());
				ecRefund.setShopAccount(shop.getShopAccount());
				ecRefund.setShopType(shop.getShopType());
				ecRefund.setEcTradeCode(storeOrder.getOrderId());
				ecRefund.setBuyerNick(user.getAccount()); //用户账号
				ecRefund.setRefundCreateTime(DateUtil.timeStamp2Date(storeOrder.getAddTime() + ""));

				// 实际退款金额
				ecRefund.setRefundFee(storeOrder.getRefundPrice());

				/**
				 * EC_WAIT_SELLER_AGREE //等待卖家同意 EC_SELLER_REFUSE_BUYER //卖家拒绝
				 * EC_WAIT_BUYER_RETURN_GOODS //等待买家退货 EC_WAIT_BUYER_RETURN_GOODS //等待买家退货
				 * EC_CLOSED //交易关闭 EC_WAIT_SELLER_AGREE //等待卖家同意 EC_CLOSED //交易关闭 EC_SUCCESS
				 * //退货成功 EC_WAIT_SELLER_AGREE //等待卖家同意
				 */
				// 退款状态： 0 未退款 1 申请中 2 已退款
				int refundStatus = ByteUtil.byteToInt(storeOrder.getRefundStatus());
				if (refundStatus == 1) {
					ecRefund.setRefundStatus("EC_WAIT_SELLER_AGREE"); // 等待卖家同意
				}
				if (refundStatus == 2) {
					ecRefund.setRefundStatus("EC_SUCCESS");// 退款成功
					// 退款时间
					ecRefund.setRefundTime(DateUtil.timeStamp2Date(storeOrder.getRefundReasonTime() + ""));
				}
				if (refundStatus >= 3) {
					ecRefund.setRefundStatus("EC_SELLER_REFUSE_BUYER");// 卖家拒绝
				}

				// 订单状态（-1 : 申请退款 -2 : 退货成功 0：待发货；1：待收货；2：已收货；3：待评价；-1：已退款）
				int status = ByteUtil.byteToInt(storeOrder.getStatus());
				// 表示货未发
				if (status == 0) {
					ecRefund.setGoodStus("BUYER_RECEIVED");
				}
				// 表示货已发未收、
				if (status == 1) {
					ecRefund.setGoodStus("BUYER_RETURNED_GOODS");
				}
				// 表示货已收
				if (status == 2 && status == 3) {
					ecRefund.setGoodStus("BUYER_RETURNED_GOODS");
				}
				// 表示退货 0 未退款 1 申请中 2 已退款
				if (refundStatus == 0) {
					ecRefund.setHasGoodReturn("y");
				} else {
					ecRefund.setHasGoodReturn("n");
				}

				ecRefund.setRefundReason(storeOrder.getRefundReasonWapExplain());
				ecRefund.setEcTradeStus(ecTrade.getEcTradeStatus());
				ecRefund.setRefundPhase("onsale");
				ecRefund.setLgstNo(storeOrder.getDeliveryId());
				// ecRefund.setRefundTimeout(DateUtil.formatStringToDate(snRefund.getStatuspasstime()));

				// 快递公司名称转换
				ecRefund.setLgstName(storeOrder.getDeliverySn());

				// 查询数据是否存在 - 平台表 ecRefund
				EcRefund ecRefundModel = ecRefundMapper.selectByPrimaryKeyEcRefund(ecRefund);
				if (ecRefundModel == null) {
					// 插入
					ecRefund.setEcRefundId(refundId);
					ecRefundMapper.insertSelectiveEcRefund(ecRefund);

					// 退款单明细
					EcRefundItem ecRefundItem = new EcRefundItem();
					ecRefundItem.setEcOid(ecOrder.getEcOid());
					ecRefundItem.setEcRefundId(refundId);
					ecRefundItem.setEcSkuCode(ecOrder.getEcSkuCode());
					ecRefundItem.setEcSkuName(ecOrder.getEcSkuName());
					ecRefundItem.setEcItemCode(ecOrder.getEcItemCode());
					ecRefundItem.setEcItemName(ecOrder.getEcItemName());
					ecRefundItem.setQty(ecOrder.getQty());
					ecRefundItem.setRefundFee(ecRefund.getRefundFee());
					ecRefundItem.setEcRefundItemId(SnoGerUtil.getUUID());
					// 插入平台表 ecRefundItem
					ecRefundItemMapper.insertSelectiveEcRefundItem(ecRefundItem);
				} else {
					// 更新
					EcRefund ecRefundUpdate = new EcRefund();
					ecRefundUpdate.setEcRefundId(ecRefundModel.getEcRefundId());
					ecRefundUpdate.setRefundStatus(ecRefund.getRefundStatus());
					ecRefundUpdate.setGoodStus(ecRefund.getGoodStus());
					ecRefundUpdate.setRefundReason(ecRefund.getRefundReason());
					// 实际退款金额
					ecRefundUpdate.setRefundFee(ecRefund.getRefundFee());
					ecRefundUpdate.setLgstNo(ecRefund.getLgstNo());
					ecRefundUpdate.setHasGoodReturn(ecRefund.getHasGoodReturn());
					ecRefundUpdate.setGoodStus(ecRefund.getGoodStus());
					ecRefundMapper.updateByPrimaryKeySelectiveEcRefund(ecRefundUpdate);
				}
			}
		}
		return new BaseResponse();
	}
}
